package com.fand.manager.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.fand.stater.model.SysUserDetailDTO;
import com.fand.manager.entity.SysUser;
import com.fand.manager.service.ISysUserRoleService;
import com.fand.manager.service.ISysUserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Author: zhangjiabin
 * Email: javaboyok@163.com
 * CreateDate: 2021/6/15
 * Version: 1.0
 */
@Service
public class SysUserDetailService implements UserDetailsService {

    @Resource
    private ISysUserService     sysUserService;
    @Resource
    private ISysUserRoleService sysUserRoleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findUserByUserCode(username);

        if(Objects.isNull(sysUser.getUserName())){
            throw new UsernameNotFoundException("用户信息为空");
        }

        List<String> resources = sysUserRoleService.listResourcesByUserCode(username);
        List<SimpleGrantedAuthority> authorities = resources.parallelStream().map(e -> e.trim().length() > 0 ? new SimpleGrantedAuthority(e.trim()) : new SimpleGrantedAuthority("login")).collect(Collectors.toList());
        return new SysUserDetailDTO(sysUser.getId(),sysUser.getUserName(),sysUser.getUserCode(), sysUser.getPassword(), authorities);
    }
}
